package io.yizoo.core;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.cache.Cache;
import io.elm.core.saas.SpringDataSourceConfig;
import io.yizoo.config.WorkWeixinConfig;
import io.yizoo.system.util.HttpClientUtils;
import io.yizoo.system.util.JDBCUtils;
import io.yizoo.system.util.wechat.cache.WorkWeiXinCache;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Map;

@Service
public class LoginWorkWeixinService {
    @Autowired
    private WorkWeixinConfig workWeixinConfig;
    @Autowired
    private Map<String,Cache<String,String>> cacheMap;
    @Autowired
    private SpringDataSourceConfig springDataSourceConfig;
    public String getAccessToken(String corpId) {
        Cache<String, String> cache = cacheMap.get(WorkWeiXinCache.ACCESS_TOKEN_CACHE);
        if (cache == null){
            throw new RuntimeException("缓存未初始化！");
        }
        if (cache.getIfPresent(corpId) != null) {
            return cache.getIfPresent(corpId);
        }
        Map<String, String> enterpriseConfig = getEnterpriseConfig(corpId);
        String permanentCode = enterpriseConfig.get("permanent_code");
        String suiteToken = getSuiteToken();
        String url = "https://qyapi.weixin.qq.com/cgi-bin/service/get_corp_token?suite_access_token="+suiteToken;
        Map<String, Object> param = new HashMap<>();
        param.put("auth_corpid", corpId);
        param.put("permanent_code", permanentCode);
        String result = HttpClientUtils.doPost(url, param);
        System.out.println("获取accessToken："+result);
        if (result == null) {
            return null;
        }
        JSONObject jsonObject = JSONObject.parseObject(result);
        String accessToken = jsonObject.getString("access_token");
        cache.put(corpId, accessToken);
        return accessToken;



    }

    public String getAgentId(@RequestParam("corpId") String corpId) {
        Cache<String, String> cache = cacheMap.get(WorkWeiXinCache.AGENT_ID_CACHE);
        if (cache == null) {
            throw new RuntimeException("缓存未初始化！");
        }
        if (cache.getIfPresent(corpId) != null) {
            return cache.getIfPresent(corpId);
        }
        Map<String, String> enterpriseConfig = getEnterpriseConfig(corpId);
        String agentId = enterpriseConfig.get("agentId");
        cache.put(corpId, agentId);
        return  agentId;

    }

    public Map<String,String> getEnterpriseConfig(String corpId) {
        String sql = "select * from work_weixi_enterprise_config where corp_id = ?";
        JDBCUtils jdbcUtils = new JDBCUtils(springDataSourceConfig);
        //jdbcUtils.beginTransaction();
        try(ResultSet rs = jdbcUtils.executeQuery(sql, corpId)){
            Map<String, String> map = new HashMap<>();
            while (rs.next()) {
                map.put("agentId", rs.getString("agent_id"));
                map.put("enterprise_name", rs.getString("enterprise_name"));
                map.put("corp_id", rs.getString("corp_id"));
                map.put("permanent_code", rs.getString("permanent_code"));
                map.put("detail", rs.getString("detail"));
            }
            return map;
        } catch (Exception e) {
            // jdbcUtils.rollbackTransaction();
            throw new RuntimeException("获取work_weixi_enterprise_config失败！ 错误信息：", e);
        }

    }

    /**
     * 获取suiteToken
     * @return
     */
    public String getSuiteToken() {
        try {
            System.out.println("获取suiteToken1");
            Cache<String, String> cache = cacheMap.get(WorkWeiXinCache.SUITE_TOKEN_CACHE);
            if (cache == null) {
                throw new RuntimeException("缓存未初始化！");
            }
            String suiteId = workWeixinConfig.getSuiteId();
            String suiteToken = cache.getIfPresent(suiteId);
            if (StringUtils.isNotEmpty(suiteToken)) {
                System.out.println("获取suiteToken1.5 :" + suiteToken);
                return suiteToken;
            }
            Cache<String, String> suiteTicketCache = cacheMap.get(WorkWeiXinCache.SUITE_TICKET_CACHE);
            String suiteTicket = suiteTicketCache.getIfPresent(suiteId);
            System.out.println("suiteTicketMap:"+ JSON.toJSONString(suiteTicketCache.asMap()));
            System.out.println("获取suiteToken 2 suiteTicket " + suiteTicket);
            String suiteTokenUrl = "https://qyapi.weixin.qq.com/cgi-bin/service/get_suite_token";
            Map<String,Object> paramMap = new HashMap<>();
            paramMap.put("suite_id", suiteId);
            paramMap.put("suite_secret",workWeixinConfig.getSuiteSecret());
            paramMap.put("suite_ticket", suiteTicket);
            System.out.println("获取suiteToken 3" + JSON.toJSONString(paramMap));
            String res = HttpClientUtils.doPost(suiteTokenUrl, paramMap);
            System.out.println("获取suiteToken结果："+ res);

            JSONObject jsonObject = JSONObject.parseObject(res);
            System.out.println("获取suiteToken 4");
            String suiteAccessToken = (String) jsonObject.get("suite_access_token");
            cache.put(suiteId, suiteAccessToken);
            System.out.println("获取suiteToken 5");
            return suiteAccessToken;
        } catch (Exception e) {
            throw new RuntimeException("获取suiteToken失败，错误信息：",e);
        }
    }
}
